package com.javacv.plus.extensions.image.steps;

import com.javacv.plus.core.processor.ProcessorContext;
import com.javacv.plus.core.processor.ProcessorStep;
import com.javacv.plus.extensions.image.ImageProcessor;
import com.javacv.plus.extensions.image.ProcessorResult;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.opencv.opencv_core.Mat;
import org.bytedeco.opencv.global.opencv_imgproc;

/**
 * 灰度转换步骤
 */
@Slf4j
public class GrayscaleStep implements ProcessorStep<ImageProcessor, ProcessorResult> {

    @Override
    public ProcessorResult execute(ImageProcessor processor, ProcessorContext context) throws Exception {
        Mat currentImage = context.getAttribute("currentImage");
        if (currentImage == null) {
            throw new IllegalStateException("当前图像为空");
        }

        log.debug("转换为灰度图像");

        Mat grayImage = new Mat();
        
        // 检查是否已经是灰度图像
        if (currentImage.channels() == 1) {
            log.debug("图像已经是灰度图像，跳过转换");
            grayImage = currentImage.clone();
        } else {
            // 转换为灰度图像
            opencv_imgproc.cvtColor(currentImage, grayImage, opencv_imgproc.COLOR_BGR2GRAY);
        }

        context.setAttribute("currentImage", grayImage);
        context.setAttribute("processedImage", grayImage);

        log.debug("灰度转换完成");
        return null;
    }

    @Override
    public String getStepName() {
        return "Grayscale";
    }

    @Override
    public int getPriority() {
        return 60;
    }
} 